<template>
  <el-dialog title="选择优惠券" :visible.sync="showDialog" :before-close="closeDialog" :close-on-click-modal="false"
    width="1200px" top="100px">
    <el-row type="flex" justify="space-around">
      <el-col :span="24">
        <el-form class="search clearfix" :inline="true" label-suffix="：" size="mini" :model="search">
          <!-- 筛选条件 -->
          <el-row>
            <el-form-item>
              <el-input v-model="search.couponNameOrCode" class="w300" clearable placeholder="搜索优惠券名称/编码"
                @keyup.enter.native="getList('search')">
                <el-button slot="append" icon="el-icon-search" @click="getList('search')" />
              </el-input>
            </el-form-item>
          </el-row>
        </el-form>
      </el-col>
    </el-row>
    <el-row type="flex" justify="space-around" class="border-bottom pb20">
      <el-col :span="4">
        <div class="tree-header">优惠券类型筛选</div>
        <el-tree :data="options.couponType" :props="{children: 'children', label: 'name'}" :expand-on-click-node="false"
          highlight-current default-expand-all @node-click="changeTreeNode" />
      </el-col>
      <el-col :span="20">
        <el-table ref="couponList" size="small" max-height="500" :data="list" :cell-style="$style.cellStyle"
          :header-cell-style="$style.rowClass" @select="selectRow" @select-all="selectAll">
          <el-table-column type="selection" :selectable="handleSelectable" width="55" />
          <ElTableColumn label="优惠券编码" prop="couponCode" />
          <ElTableColumn label="优惠券名称" prop="couponName" />
          <ElTableColumn label="类型">
            <template slot-scope="{row}">
              {{ row.couponType === '1' ? '直减卷' : '' }}
            </template>
          </ElTableColumn>
          <ElTableColumn label="有效期" width="300">
            <template slot-scope="{row}">
              <span v-if="row.termOfValidity > 1">
                领取 {{ row.validDays }} 天内
              </span>
              <span v-else>
                {{ row.termOfValidityStart }} - {{ row.termOfValidityStop }}
              </span>
            </template>
          </ElTableColumn>
          <ElTableColumn label="状态">
            <template slot-scope="{row}">
              <el-tag :type="options.couponStatus[row.couponStatus * 1].type">
                {{ options.couponStatus[row.couponStatus * 1].name }}
              </el-tag>
            </template>
          </ElTableColumn>
        </el-table>
        <pagination class="page tc mt10" :total="page.total" :page.sync="page.current" :limit.sync="page.size"
          @pagination="getList" />
      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button v-if="!disabled" type="primary" size="small" @click="getSelect()">确 定</el-button>
      <el-button size="small" @click="closeDialog()">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
class Search {
  constructor() {
    this.couponNameOrCode = ''; // 	优惠券名称/编码
    this.couponType = ''; // 优惠券类型
  }
}
class Page {
  constructor() {
    this.total = 0;
    this.current = 1;
    this.size = 10;
  }
}
class Options {
  constructor() {
    this.couponStatus = [
      { id: '', name: '全部状态', type: '' },
      { id: '1', name: '未生效', type: 'warning' },
      { id: '2', name: '生效中', type: 'success' },
      { id: '3', name: '已结束', type: 'danger' },
      { id: '4', name: '已作废', type: 'info' }
    ]; // 状态
    this.couponType = [
      { id: '', name: '全部类型', type: '' },
      { id: '1', name: '直减券', type: 'success' }
    ]; // 类型
  }
}
import { couponListPage } from '@/api/activity';
import pagination from '@/components/Pagination';
export default {
  name: 'Search',
  components: {
    pagination
  },
  props: {
    selectMode: {
      type: String,
      default: 'single'
    }, // 选择模式，single 单选；multiple 多选
    showDialog: {
      type: Boolean,
      default: false
    }, // 开关
    defaultDatas: {
      type: Array,
      default: () => []
    }, // 默认回显数据
    showSelected: {
      type: Boolean,
      default: false
    }, // 回显标识
    disabled: {
      type: Boolean,
      default: false
    } // 是否禁用
  },
  data () {
    return {
      page: new Page(), // 分页
      search: new Search(this.searchType), // 搜索
      options: new Options(), // 搜索项
      list: [], // 列表
      selectedDatas: []
    };
  },
  watch: {
    showDialog (newVal) {
      if (newVal) {
        this.open();
      }
    }
  },
  methods: {
    open () {
      this.selectedDatas = [];
      if (this.defaultDatas.length > 0) {
        this.selectedDatas = JSON.parse(JSON.stringify(this.defaultDatas));
      }
      this.getList('search');
    },
    // 用于已选商品进行回显
    checkedProduct () {
      if (this.showSelected) {
        // console.log('预选项', this.selectedDatas);
        this.list.forEach(item => {
          if (this.selectedDatas.includes(item.couponCode)) {
            this.$nextTick(() => {
              this.$refs['couponList'].toggleRowSelection(item, true);
            });
          }
        });
      }
    },
    // 获取商品列表
    async getList (type) {
      if (type === 'search') this.page = new Page();
      try {
        let data;
        data = await couponListPage({ ...this.page, ...this.search });
        const { records, total } = data;
        this.page.total = total * 1;
        this.list = records;
        this.checkedProduct(); // 用于已选进行回显
      } catch (e) {
        this.page.total = 0;
        this.list = [];
      }
    },
    // 是否可选
    handleSelectable (row) {
      return row.couponStatus < 3; // 只能选择生效中或者未生效的
    },
    // 切换左侧分类
    changeTreeNode (val) {
      this.search.couponType = val.id;
      this.getList();
    },
    // 关闭弹窗
    closeDialog () {
      this.search = new Search();
      this.$refs['couponList'].clearSelection();
      this.$emit('closeDialog');
    },
    // 当用户手动勾选数据行的 Checkbox 时触发的事件
    selectRow (selection, row) {
      const ids = selection.map((val) => val.couponCode);
      if (ids.includes(row.couponCode)) {
        this.addSelectGood([row]);
      } else {
        this.delSelectGood([row]);
      }
    },
    // 多选添加
    addSelectGood (arr) {
      arr.forEach(item => {
        if (!this.selectedDatas.includes(item.couponCode) && item.couponStatus < 3) {
          this.selectedDatas.push(item.couponCode);
        }
      });
    },
    // 多选删除
    delSelectGood (arr) {
      arr.forEach(item => {
        if (this.selectedDatas.includes(item.couponCode)) {
          const index = this.selectedDatas.findIndex(val => val === item.couponCode);
          this.selectedDatas.splice(index, 1);
        }
      });
    },
    // 当用户手动勾选全选 Checkbox 时触发的事件
    selectAll (selection) {
      if (selection.length <= 0) {
        this.delSelectGood(this.list);
      } else {
        this.addSelectGood(this.list);
      }
    },
    // 确定选项
    getSelect () {
      Array.from(new Set(this.selectedDatas));
      const selected = this.selectedDatas; // 选项赋值，用于筛选框回显
      this.$emit('getSelect', selected);
      this.closeDialog();
    }
  }
};
</script>

<style scoped lang="scss">
.tree-header {
  height: 40px;
  background: #f9fafc;
  color: #909399;
  font-size: 12px;
  font-weight: bold;
  line-height: 40px;
  text-align: center;
  border-bottom: 1px solid #ebeef5;
}
.border-bottom {
  border-bottom: 1px solid #ebeef5;
}
</style>
